package com.hebau.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hebau.usercenter.common.ErrorCode;
import com.hebau.usercenter.exception.BusinessException;
import com.hebau.usercenter.model.domain.User;
import com.hebau.usercenter.mapper.UserMapper;
import com.hebau.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.hebau.usercenter.constant.UserConstant.USER_LOGIN_STATE;
/**
* @author 86183
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-03-07 17:21:04
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    private static final String SALT = "hebau";

    @Resource
    private UserMapper userMapper;
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String uniqueCode) {
        // 1.校验 账号密码不能为空
        if (StringUtils.isAllBlank(userAccount,userPassword,checkPassword, uniqueCode)){
            throw new BusinessException(ErrorCode.PARAM_NULL, "账号密码不能为空");
        }
        // 2.校验账号 长度不小于4位
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAM_ERROR, "账号长度不能小于 4 位");
        }
        // 3.校验密码长度 不小于8位
        if (userPassword.length() < 8 || checkPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAM_ERROR, "密码长度不能小于 8 位");
        }
        // 4.校验密码是否相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "两次密码输入不同");
        }
        // 5.账户是否包含特殊字符；
        String regex = "^[a-zA-Z0-9_]+$";
        if (!userAccount.matches(regex)){
            throw new BusinessException(ErrorCode.PARAM_ERROR, "账户包含特殊字符");
        }
        // 6.账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        Long count = userMapper.selectCount(queryWrapper);
        if (count > 0){
            // 账号已重复
           throw new BusinessException(ErrorCode.PARAM_ERROR, "账号已被注册");
        }
        // 6.唯一编码不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uniqueCode", uniqueCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0){
            // 该唯一编码已被使用
            throw new BusinessException(ErrorCode.PARAM_ERROR, "该唯一编码已被使用");
        }
        // 用户信息校验通过
        // 7.进行md5加密处理,spring 框架自带加密工具 DigestUtils
        String password = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 8.将处理过的用户密码插入 user 表中
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(password);
        user.setUniqueCode(Integer.parseInt(uniqueCode));
        int res = userMapper.insert(user);
        if (res <= 0){
            log.info("用户信息插入失败");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "用户信息插入失败");
        }

        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1.校验 账号密码不能为空
        if (StringUtils.isAllBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAM_NULL, "用户账号或密码为空");
        }
        // 2.校验账号 长度不小于4位
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAM_ERROR, "账号长度不能小于 4 位");
        }
        // 3.校验密码长度 不小于8位
        if (userPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAM_ERROR, "密码长度不能小于 8 位");
        }
        // 4.账户是否包含特殊字符；
        String regex = "^[a-zA-Z0-9_]+$";
        if (!userAccount.matches(regex)){
            throw new BusinessException(ErrorCode.PARAM_ERROR, "账号格式错误");
        }
        // 5.校验密码是否正确，和数据库中的密文密码作对比，即查询用户是否存在
        userPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", userPassword);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            // 用户不存在
            throw new BusinessException(ErrorCode.PARAM_ERROR, "用户不存在，请先注册");
        }
        // 用户信息脱敏
        User safetyUser = getSafetyUser(user);

        // 记录用户状态 session
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);

        return safetyUser;
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        // 移除用户登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    /**
     * 用户脱敏
     * @param user 用户
     * @return 安全用户
     */
    public User getSafetyUser(User user){
        User safetyUser = new User();
        safetyUser.setId(0L);
        safetyUser.setUsername(user.getUsername());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setGender(user.getGender());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setUserStatus(user.getUserStatus());
        safetyUser.setCreateTime(user.getCreateTime());
        safetyUser.setUpdateTIme(user.getUpdateTIme());
        safetyUser.setIsDelete(0);
        safetyUser.setUserRole(user.getUserRole());
        safetyUser.setUniqueCode(user.getUniqueCode());
        return safetyUser;
    }


}




